package com.whl.sm.service.impl.dynamic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.dynamic.VDynamicMapper;
import com.whl.sm.model.dynamic.VDynamic;
import com.whl.sm.model.notice.Attachment;
import com.whl.sm.service.dynamic.VDynamicService;
import com.whl.sm.service.notice.AttachmentService;
import com.whl.sm.service.system.OrgUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2022-01-15
 */
@Slf4j
@Service
public class VDynamicServiceImpl extends ServiceImpl<VDynamicMapper, VDynamic> implements VDynamicService {

    @Autowired
    private OrgUserService orgUserService;


    @Autowired
    private AttachmentService attachmentService;

    @Override
    public Result update(VDynamic vDynamic) {
        String userId = orgUserService.getCurrentUserId();
        try{
            vDynamic.setOperator(userId);
            if (Objects.isNull(vDynamic.getId())){
                getBaseMapper().insert(vDynamic);
            }else {
                getBaseMapper().updateById(vDynamic);
            }

        }catch (Exception e){
            log.error("动态信息更新异常:"+e.getMessage());
        }
        return Result.ok();
    }

    @Override
    public Result publish(String content, String tempId) {
        try{
            VDynamic insert = new VDynamic();
            insert.setContent(content);
            Result insertRt = this.update(insert);
            if (!insertRt.isOk()){
                return insertRt;
            }else {
                List<Attachment> linkImg = attachmentService.list(new QueryWrapper<Attachment>().eq("data_id",tempId));
                for (Attachment item : linkImg){
                    item.setDataId(insert.getId());
                    attachmentService.update(item);
                }
            }
        }catch (Exception e){
            log.error("动态发布异常=================>"+e.getMessage());
        }
        return Result.ok();
    }
}
